package com.bistu.sim.xwy.news;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bistu.sim.xwy.news.Adapter.SalerAdapter;
import com.bistu.sim.xwy.news.Http.WeatherHttpUtil;
import com.bistu.sim.xwy.news.Other.SalerGoodsActivity;
import com.bistu.sim.xwy.news.UserMode.FocusActivity;
import com.bistu.sim.xwy.news.UserMode.MessageActivity;
import com.bistu.sim.xwy.news.UserMode.MineActivity;
import com.bistu.sim.xwy.news.UserMode.PostActivity;
import com.bistu.sim.xwy.news.UserMode.PublishActivity;
import com.bistu.sim.xwy.news.Weather.UpdateService;
import com.bistu.sim.xwy.news.Weather.Utility;
import com.bistu.sim.xwy.news.domain.Saler;
import com.bistu.sim.xwy.news.gson.Weather;
import com.bistu.sim.xwy.news.gson.WeatherResults;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private TextView tvFirstDayDate;
    private TextView tvFirstDayPhe;
    private TextView tvFirstDayHigh;
    private TextView tvFirstDayLow;
    private TextView mycity;
    private TextView temperatureText;
    private TextView caseText;
    private SwipeRefreshLayout refreshLayout;
    private LinearLayout loading;


    private LinearLayout index_bottom_bar_home;
    private LinearLayout index_bottom_bar_dynamic_state;
    private LinearLayout index_bottom_bar_me;
    private LinearLayout index_bottom_bar_integral;
    private LinearLayout index_bottom_bar_post;
    private ImageView index_botton_bar_scan;
    private ImageView index_bottom_bar_post_image;
    private ImageView index_bottom_bar_home_image;
    private ImageView index_bottom_bar_dynamic_state_image;
    private ImageView index_bottom_bar_integral_image;
    private ImageView index_bottom_bar_me_image;

    private static final String TAG = "MainActivity";
    private List<Saler> list;
    private Saler saler;
    private SalerAdapter adapter;
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        DoGet();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                saler = list.get(position);
                Intent intent = new Intent(MainActivity.this, SalerGoodsActivity.class);
                String usr_id = String.valueOf(saler.getBus_user_id());
                intent.putExtra("id",usr_id);
                intent.putExtra("desc",saler.getBus_user_desc());
                intent.putExtra("image",saler.getBus_user_image());
                intent.putExtra("name",saler.getBus_user_name());
                startActivity(intent);
            }
        });
    }



    public void GetrequestWeather(String cityPinYin){
        String url="https://api.seniverse.com/v3/weather/daily.json?key=SeCotTi-iRxdqM2u0&location=" + cityPinYin + "&language=zh-Hans&unit=c&start=0&days=5";
        final Utility util=new Utility();
        Utility.showProgressDialog(MainActivity.this);
        WeatherHttpUtil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                assert response.body() != null;
                final String weatherData=response.body().string();
                Log.e("MainActivity","得到的数据"+weatherData);
                final Weather weatherInfo= Utility.handleWeatherRsponse(weatherData);
                if(weatherInfo!=null){
                    SharedPreferences.Editor editor= getSharedPreferences("weather",MODE_PRIVATE).edit();
                    editor.putString("WEATHER", weatherData);
                    editor.putBoolean("isSelected",true);
                    editor.apply();
                }
                Utility.dismiss();
                showWeatherInfo(weatherInfo);
            }
        });
    }
    private void showWeatherInfo(final Weather weatherInfo){
        runOnUiThread(() -> {

            WeatherResults results=weatherInfo.getResults().get(0);
            String cityName=results.getLocation().getName();//城市名称


            //将3天内的天气数据获得后存入二维数组
            String [] [] resultDaily=new String[3][5];
            for(int i=0;i<3;i++){
                for(int j=0;j<4;){
                    resultDaily[i][j]=results.getDaily().get(i).getDate();j++;
                    resultDaily[i][j]=results.getDaily().get(i).getText_day();j++;
                    resultDaily[i][j]=results.getDaily().get(i).getHigh();j++;
                    resultDaily[i][j]=results.getDaily().get(i).getLow();j++;
                }
            }
            mycity.setText(cityName);
            temperatureText.setText(resultDaily[0][2]+"℃");
            caseText.setText(resultDaily[0][1]);

            for(int j=0;j<4;){
                //Log.e("resultDaily",resultDaily[0][j]);
                tvFirstDayDate.setText(resultDaily[0][j]);j++;
                tvFirstDayPhe.setText(resultDaily[0][j]);j++;
                tvFirstDayHigh.setText(resultDaily[0][j]+"℃");j++;
                tvFirstDayLow.setText(resultDaily[0][j]+"℃");j++;
            }


        });
    }

    private void initView() {

        temperatureText=findViewById(R.id.temperature_text);
        caseText=findViewById(R.id.case_text);
        mycity=findViewById(R.id.my_city);
        tvFirstDayDate = findViewById(R.id.tv_firstday_date);
        tvFirstDayPhe=findViewById(R.id.tv_firstday_phe);
        tvFirstDayHigh=findViewById(R.id.tv_firstday_high);
        tvFirstDayLow=findViewById(R.id.tv_firstday_low);

        listView = (ListView)findViewById(R.id.saler_list) ;

        refreshLayout=findViewById(R.id.swipe_refresh);
        loading =findViewById(R.id.loading);

        index_bottom_bar_home = findViewById(R.id.index_bottom_bar_home);
        index_bottom_bar_dynamic_state = findViewById(R.id.index_bottom_bar_dynamic_state);
        index_bottom_bar_me=findViewById(R.id.  index_bottom_bar_me);
        index_bottom_bar_integral=findViewById(R.id.index_bottom_bar_integral);
        index_botton_bar_scan=findViewById(R.id.index_bottom_bar_scan);
        index_bottom_bar_post = findViewById(R.id.index_bottom_post);

        index_bottom_bar_home_image = (ImageView) findViewById(R.id.index_bottom_bar_home_image);
        index_bottom_bar_dynamic_state_image = (ImageView) findViewById(R.id.index_bottom_bar_dynamic_state_image);
        index_bottom_bar_integral_image = (ImageView) findViewById(R.id.index_bottom_bar_integral_image);
        index_bottom_bar_me_image = (ImageView) findViewById(R.id.index_bottom_bar_me_image);
        index_bottom_bar_post_image = (ImageView) findViewById(R.id.index_bottom_post_img);

        index_bottom_bar_home_image.setImageResource(R.mipmap.index_bottom_bar_home_select);

        index_bottom_bar_home.setOnClickListener(this);
        index_bottom_bar_dynamic_state.setOnClickListener(this);
        index_bottom_bar_integral.setOnClickListener(this);
        index_bottom_bar_me.setOnClickListener(this);
        index_botton_bar_scan.setOnClickListener(this);
        index_bottom_bar_post.setOnClickListener(this);

        Intent intent=new Intent();
        intent.setClass(MainActivity.this, UpdateService.class);
        //startService(intent);
        GetrequestWeather("chengdu");
        refreshLayout.setColorSchemeResources(R.color.primary);
        refreshLayout.setOnRefreshListener(() -> {
            Toast.makeText(MainActivity.this,"刷新成功",Toast.LENGTH_SHORT).show();
            //Log.e("MainActivity","返回城市的拼音"+cityPinYin);
            //心知天气的api
            GetrequestWeather("chengdu");
            refreshLayout.setRefreshing(false);
        });
    }

    public void DoGet(){
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(8000, TimeUnit.MILLISECONDS)
                .build();
        Request request = new Request.Builder()
                .get()
                .url(getString(R.string.saler_url)+"bus/findAll")
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG,"请求失败"+e.toString());

            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String body=response.body().string();
                Log.e(TAG,"请求成功"+response.code());
                Log.e(TAG,"请求数据"+body);
                Gson gson = new Gson();
                list = gson.fromJson(body, new TypeToken<List<Saler>>(){}.getType());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter = new SalerAdapter(MainActivity.this,list);
                        listView.setAdapter(adapter);
                    }
                });
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case  R.id.index_bottom_bar_home:
                Intent intent = new Intent(this,MainActivity.class);
                MainActivity.this.finish();
                startActivity(intent);
                overridePendingTransition(0,0);
                break;
            case  R.id.index_bottom_bar_integral:
                Intent intent1 = new Intent(this, MessageActivity.class);
                startActivity(intent1);
                MainActivity.this.finish();
                overridePendingTransition(0,0);
                break;
            case  R.id.index_bottom_bar_dynamic_state:
                Intent intent2 = new Intent(this, FocusActivity.class);
                startActivity(intent2);
                MainActivity.this.finish();
                overridePendingTransition(0,0);
                break;
            case  R.id.index_bottom_bar_me:
                Intent intent3 = new Intent(this, MineActivity.class);
                startActivity(intent3);
                MainActivity.this.finish();
                overridePendingTransition(0,0);
                break;
            case R.id.index_bottom_post:
                Intent intent4 = new Intent(this, PostActivity.class);
                startActivity(intent4);
                MainActivity.this.finish();
                overridePendingTransition(0,0);
                break;
            case R.id.index_bottom_bar_scan:
                Intent intent5 = new Intent(this, PublishActivity.class);
                startActivity(intent5);
                break;
        }
    }
}
